// 引入fs模块
const fs = require('fs');
// 引入mysql模块 相对路径
const sql = require('../model/config');
// 发布文章
module.exports.publish = async function(req,res,next){
    // console.log(req.file);
    // console.log("=======分割线======");
    // console.log(req.body);

    // res.send('ok');

    // {
    //     fieldname: 'thumb',
    //     originalname: 'aa.jpeg',
    //     encoding: '7bit',
    //     mimetype: 'image/jpeg',
    //     destination: 'E:\\2021WEB05\\Nodejs\\day17\\Hellom\\public\\img\\',
    //     filename: 'e3a9a052a6929cf10204ff2da0a2d14e',
    //     path: 'E:\\2021WEB05\\Nodejs\\day17\\Hellom\\public\\img\\e3a9a052a6929cf10204ff2da0a2d14e',
    //     size: 69253
    // }
    // =======分割线======
    // [Object: null prototype] {
    //     sort_id: '2',
    //     title: 'aaa',
    //     author: '风月笑平生',
    //     subhead: '风月博客',
    //     intro: 'IT，web, ui ,java',
    //     'test-editor-markdown-doc': '测试收拾收拾收拾收拾书'
    // }

    // const content = req.body['test-editor-markdown-doc'];  //富文本默认的name值为test-editor-markdown-doc,如果给textarea设置了name="content",后端是通过content接收参数
    const { title, author, subhead, intro, content } = req.body;
    const sort_id = Number(req.body.sort_id);
    console.log(sort_id, title, author, subhead, intro, content);
    let thumb;
    let isFile = false;
    // 是否上传了文件
    if (req.file) {
        //判断文件类型
        const fileName = req.file.originalname.toLowerCase();
        const fileSize = req.file.size;
        const name = fileName.substr(fileName.lastIndexOf('.')+1,fileName.length);
        if (!/(gif|jpg|jpeg|png|bmp|webp)$/.test(name) || fileSize >= 1048576 ) {
            // alert +=  "图片类型必须是.gif,jpeg,jpg,png,bmp,webp中的一种,且图片大小不能大于1M！";
            //res.send("<script>alert('图片类型必须是.gif,jpeg,jpg,png,bmp,webp中的一种,且图片大小不能大于1M！');location.href='/article'</script>");
            isFile = true;
        } else {
            const oldPath = req.file.path;
            // 不会去重
            // var newPath = req.file.path + path.extname(req.file.originalname);
            // 会去重，不能上传相同名称的图片
            const newPath = req.file.destination + req.file.originalname;
            // 上传图片重命名
            fs.renameSync(oldPath,newPath);
            // 把图片的服务端的请求路径存储到数据库中
            thumb = 'img/'+ req.file.originalname;
            isFile = false;
        }
    }else{
        thumb = 'img/html5.jpg';
    }

    if (isFile) {
        res.send("<script>alert('图片类型必须是.gif,jpeg,jpg,png,bmp,webp中的一种,且图片大小不能大于1M！');location.href='/article'</script>");
    }else{
        try {
            await sql(`insert into ?? values (NULL,?,?,?,?,?,?,?,NULL,NULL,now(),now(),now())`,['article',sort_id, thumb, title, author, subhead, intro, content]);
            res.send("<script>alert('发布文章成功');location.href='/'</script>");
        } catch (error) {
            next(error);
        } 
    }


}

// 点赞
module.exports.downs = async function(req,res){
    console.log(req.body);  
    const id =  Number(req.body.id);
    const downs = req.body.downs;
    const isDowns = req.body.isDowns;
    const nickname = req.body.nickname;
    // 给点赞表管理点赞功能
    let thumbs = await sql("select * from thumbs_up where nickname = ? and article_id = ?",[nickname,id]);    
    if ( isDowns === 'false' ) {
        try {
            await sql('update article set downs = ? where article_id = ?',[downs,id]);
            
            if (thumbs.length === 0) {
                await sql("insert into thumbs_up values (NULL,?,?,?)",[nickname,id,1]);
            }else{
                await sql("update thumbs_up set on_off = ? where nickname = ?",[1,nickname]);
            }

            res.send({
                code:200,
                msg:"点赞成功"
            });
        } catch (error) {
            res.send({
                code:500,
                msg:"点赞失败"
            });
            next(error);
        }
    }else{
        try {
            await sql('update article set downs = ? where article_id = ?',[downs,id]);
            if (thumbs.length === 0) {
                await sql("insert into thumbs_up values (NULL,?,?,?)",[nickname,id,1]);
            }else{
                await sql("update thumbs_up set on_off = ? where nickname = ?",[0,nickname]);
            }
            res.send({
                code:200,
                msg:"取消点赞成功"
            });
        } catch (error) {
            res.send({
                code:500,
                msg:"点赞失败"
            });
            next(error);
        }
    }

    // res.send("ok");


    
    
}